package znet

import (
	"errors"
	"fmt"
	"sync"
	ziface "zinx/Ziface"
)


type ConManager struct {

	Connections map[uint32] ziface.IConnection
	//读写锁
	conlock sync.RWMutex
}



func NewConManger() *ConManager{
	return &ConManager{
		Connections: make(map[uint32]ziface.IConnection),
	}
}

func(cmg *ConManager) Add(con ziface.IConnection){
	cmg.conlock.Lock()
	defer cmg.conlock.Unlock()
	cmg.Connections[con.GetID()]=con	
	fmt.Println("connection add to ConnManager successfully: conn num = ", cmg.Len())
}

func(cmg *ConManager) Remove(con ziface.IConnection){
	cmg.conlock.Lock()
	defer cmg.conlock.Unlock()
	delete(cmg.Connections,con.GetID())
	fmt.Println("connection Remove ConnID=",con.GetID(), " successfully: conn num = ", cmg.Len())
}

func(cmg *ConManager)Get(connID uint32) (ziface.IConnection, error){
	cmg.conlock.RLock()
	defer cmg.conlock.RUnlock()
	if conn,ok:=cmg.Connections[connID];ok{
		return conn,nil
	}else{
		return nil,errors.New("connection not found")
	}
}

func(cmg *ConManager) Len() int{
	return len(cmg.Connections)
} 

func(cmg *ConManager)ClearConn() {
	//保护共享资源Map 加写锁
	cmg.conlock.Lock()
	defer cmg.conlock.Unlock()

	for conid,con:=range cmg.Connections {
		con.Stop()
		delete(cmg.Connections,conid)	
	}
	fmt.Println("Clear All Connections successfully: conn num = ", cmg.Len())
}